import { createRouter, createWebHistory } from 'vue-router'
import { getCurrentUser } from '../api/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/chat',
      name: 'chat',
      component: () => import('../views/ChatView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/price-history',
      name: 'priceHistory',
      component: () => import('../views/PriceHistoryView.vue')
    }
  ]
})

// 路由守卫：检查是否需要登录
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 已登录用户访问登录页，直接跳转到聊天页（避免验证）
  if (to.path === '/login' && token) {
    next('/chat')
    return
  }
  
  // 需要认证的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      // 没有token，跳转登录
      next('/login')
      return
    }
    
    // 有token，验证token是否有效
    try {
      await getCurrentUser(token)
      // token有效，继续访问
      next()
    } catch (error) {
      // token无效或过期，清除并跳转登录
      console.error('Token验证失败:', error)
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      next('/login')
    }
  } else {
    // 不需要认证的页面，直接访问
    next()
  }
})

export default router

